package myJDBC.lowLevel;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import myJDBC.*;
public class AttrObjectTypes {
	//in-> object_type_id;  out-> Array( Attribute_id, bind_id)
			public static  ArrayList<Integer> returnAttrObjectTypes(int objTypeId){
				ArrayList<Integer> al = new ArrayList<Integer>();
			/*	String selectAttributes = "select t1.\"attribute_id\""
						+ "from \"attr_object_types\" t1 "
						+ "where t1.\"object_type_id\"="+objTypeId+" and t1.\"bind_id\" in("
						+ "select t2.\"bind_id\" from \"bind\" t2 where t2.\"name\"='public')";//только public???*/
				StringBuilder selectAttributes = new StringBuilder();
				   selectAttributes.append("select t1.\"attribute_id\", t1.\"bind_id\" ")
								   .append("from \"attr_object_types\" t1 ")
								   .append("where t1.\"object_type_id\"=? ");
				if (myConnection.dbConnection != null) {
					try (PreparedStatement pstmt = myConnection.dbConnection
					                .prepareStatement(selectAttributes.toString())) {
							   pstmt.setInt(1, objTypeId);
							   pstmt.executeUpdate(); 
							   ResultSet rs = pstmt.executeQuery();		
						Integer tmp;
						while (rs.next()) {
							tmp = rs.getInt(1);
							al.add(tmp);
							tmp=rs.getInt(2);
							//if(tmp==0)
							al.add(tmp);
						}
					} catch (SQLException e) {
							System.out.println(e.getMessage());
					}
					return al;
				} else
					return null;		
			}
			
			public static void createAttrObjectTypes(int objTypeId, ArrayList<String> attributes, ArrayList<String> binds) throws NumberFormatException, SQLException{
				for(int i=0; i<attributes.size(); i++){
					createAttrObjectType(objTypeId, Integer.parseInt(attributes.get(i)), Integer.parseInt(binds.get(i)));
				}
			}
			
			public static void createAttrObjectType(int objTypeId, int attribute, int bind) throws SQLException{
				PreparedStatement pstmt = null;
				try {
					pstmt = myConnection.dbConnection.prepareStatement("insert into \"attr_object_types\"(\"object_type_id\" ,\"attribute_id\", \"bind_id\") values (?,?,?)");
					pstmt.setInt(1, objTypeId);
					pstmt.setInt(2, attribute);
					pstmt.setInt(3, bind);
					pstmt.executeUpdate();
				} finally {
					if (pstmt != null)
						pstmt.close();
				}
			}
}
